﻿package com.projects.xenia.add_activities;


import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.Calendar;
import com.projects.xenia.MainCustomersListActivity;
import com.projects.xenia.R;
import com.projects.xenia.global_modules.MainGlobalModule;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnKeyListener;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.KeyEvent;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.ImageView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;

public class Activity_ExtReports extends Activity {
	
	private static String CurrentURLString;
	private static final String LocalURLString = "http://"+MainGlobalModule.SettingsCollection.get("LocalWebServiceURL");
	private static final String PrimaryURLString = "http://"+MainGlobalModule.SettingsCollection.get("PrimaryWebServiceURL");	
	private static final String SecondaryURLString = "http://"+MainGlobalModule.SettingsCollection.get("SecondaryWebServiceURL");	
	
	private Context Ctx;
	
	private TextView rep_rep_label;	
	private Button rep_replist_btn;
	
	private TextView rep_datebeg_label;
	private Button rep_datebeg_btn;
	
	private TextView rep_dateend_label;
	private Button rep_dateend_btn;
	
	private TextView rep_acctype_label;
	private Button rep_acctype_btn;
	
	private TextView rep_firm_label;
	private Button rep_firm_btn;
	
	private TextView rep_customer_label;
	private Button rep_customer_btn;
	
	private ImageView rep_repgo_ibtn;
	private ImageView rep_replist_ibtn;
	private ImageView rep_back_ibtn;
	
	private Cursor ReportsCursor;	
	private Cursor ReportsFieldsCursor;
	private Cursor AccTypeCursor;
	private Cursor FirmCursor;
	
	private Button Current; 
	
	private final int IDR_CustomerSelect = 0;
	
	private ProgressDialog pd;
	
	private void SetCurrentURLString () {
		
		CurrentURLString = PrimaryURLString;
		
	}
	
	private URL GetWebServiceURL (String URLString) {
		
		URL xUrl;
		
		try {
			xUrl = new URL(URLString.concat("/maWebService/XeniaPostHandler.ashx"));
		} catch (MalformedURLException e) {
			xUrl = null;
			e.printStackTrace();
		}
		
		return xUrl; 
	}

	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	
		requestWindowFeature(Window.FEATURE_NO_TITLE);            
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
	
		setContentView(R.layout.reports_form);
		
		Ctx = this;

		pd = new ProgressDialog(Ctx);		
		pd.setTitle("Запрос данных");
		pd.setMessage("Выполнение запроса и загрузка данных");
		pd.setProgressStyle(ProgressDialog.STYLE_SPINNER);
		
		rep_rep_label = (TextView)findViewById(R.id.rep_rep_label);	
		rep_replist_btn = (Button)findViewById(R.id.rep_replist_btn);
			
		rep_datebeg_label= (TextView)findViewById(R.id.rep_datebeg_label);		
		rep_datebeg_btn = (Button)findViewById(R.id.rep_datebeg_btn);
		rep_datebeg_btn.setTag(Calendar.getInstance());
		rep_datebeg_btn.setText(MainGlobalModule.FormatDate(Calendar.getInstance().getTime()));
		rep_datebeg_btn.setOnClickListener(SetDateTime);		
		
		rep_dateend_label= (TextView)findViewById(R.id.rep_dateend_label);		
		rep_dateend_btn = (Button)findViewById(R.id.rep_dateend_btn);
		rep_dateend_btn.setTag(Calendar.getInstance());
		rep_dateend_btn.setText(MainGlobalModule.FormatDate(Calendar.getInstance().getTime()));
		rep_dateend_btn.setOnClickListener(SetDateTime);		
	
		rep_acctype_label = (TextView)findViewById(R.id.rep_acctype_label);		
		rep_acctype_btn = (Button)findViewById(R.id.rep_acctype_btn);		
		rep_acctype_btn.setOnClickListener(new OnClickListener() {			
			@Override
			public void onClick(View v) {
				AlertDialog.Builder adb = new AlertDialog.Builder(Ctx);
				SimpleCursorAdapter ad = new SimpleCursorAdapter (Ctx,android.R.layout.select_dialog_item, AccTypeCursor,new String[] {"descr"}, new int [] {android.R.id.text1});
				adb.setAdapter(ad, AccTypeCursor_DialogSelect);
				adb.create();
				adb.show();
			}
		});
		
		
	
		rep_firm_label = (TextView)findViewById(R.id.rep_firm_label);		
		rep_firm_btn = (Button)findViewById(R.id.rep_firm_btn);
		rep_firm_btn .setOnClickListener(new OnClickListener() {			
			@Override
			public void onClick(View v) {
				AlertDialog.Builder adb = new AlertDialog.Builder(Ctx);
				SimpleCursorAdapter ad = new SimpleCursorAdapter (Ctx,android.R.layout.select_dialog_item, FirmCursor,new String[] {"descr"}, new int [] {android.R.id.text1});
				adb.setAdapter(ad, FirmCursor_DialogSelect);
				adb.create();
				adb.show();
			}
		});
		
		
	
		rep_customer_label = (TextView)findViewById(R.id.rep_customer_label);			
		rep_customer_btn = (Button)findViewById(R.id.rep_customer_btn);
		rep_customer_btn.setTag("");
		rep_customer_btn.setText("Не выбран …");
		rep_customer_btn.setOnClickListener(new OnClickListener() {			
			@Override
			public void onClick(View v) {
				Intent CustomerSelectintent = new Intent();
				CustomerSelectintent.putExtra("customer_id", (String)rep_customer_btn.getTag());
				CustomerSelectintent.setClass(Ctx,MainCustomersListActivity.class);
		        startActivityForResult (CustomerSelectintent,IDR_CustomerSelect);				
			}
		});
		
		rep_repgo_ibtn = (ImageView)findViewById(R.id.rep_launch);
		rep_repgo_ibtn.setOnClickListener(rep_repgo_ibtn_click);
		
//		rep_replist_ibtn = (ImageView)findViewById(R.id.rep_replist_ibtn);
	
		rep_back_ibtn = (ImageView)findViewById(R.id._backward);
		rep_back_ibtn.setOnClickListener(new OnClickListener() {		
		@Override
		public void onClick(View v) {
			finish ();
			}
		});
		
		GetAccTypeCursor ();
		GetFirmCursor ();
		GetReportsCursor ();
		
		
		rep_replist_btn.setOnClickListener(new OnClickListener() {			
			@Override
			public void onClick(View v) {
				AlertDialog.Builder adb = new AlertDialog.Builder(Ctx);
				SimpleCursorAdapter ad = new SimpleCursorAdapter (Ctx,android.R.layout.select_dialog_item, ReportsCursor,new String[] {"descr"}, new int [] {android.R.id.text1});
				adb.setAdapter(ad, ReportsCursor_DialogSelect);
				adb.create();
				adb.show();
			}
		});
		
		ProcessWidgetsByReportItem ();
		
}

	private OnClickListener SetDateTime = new OnClickListener () {
		@Override
		public void onClick(View v) {
			
			Current = (Button)v;
			Calendar WidgetDate = (Calendar)v.getTag();			
			DatePickerDialog dpd = new DatePickerDialog(Ctx, DatePickerDialogSelect, WidgetDate.get(Calendar.YEAR), WidgetDate.get(Calendar.MONTH), WidgetDate.get(Calendar.DAY_OF_MONTH));			
			dpd.show();
			
		}		
	};
	
	private DatePickerDialog.OnDateSetListener DatePickerDialogSelect = new OnDateSetListener() {		
		@Override
		public void onDateSet(DatePicker view, int year, int monthOfYear,int dayOfMonth) {
						
			Calendar WidgetDate = Calendar.getInstance();
			WidgetDate.set(year, monthOfYear, dayOfMonth);
			Current.setTag(WidgetDate);
			Current.setText(MainGlobalModule.FormatDate(WidgetDate.getTime()));
			
		}
	};
	
	private void HideAll () {
	
		rep_datebeg_label.setVisibility(View.GONE);
		rep_datebeg_btn.setVisibility(View.GONE);
		
		rep_dateend_label.setVisibility(View.GONE);
		rep_dateend_btn.setVisibility(View.GONE);			

		rep_customer_label.setVisibility(View.GONE);			
		rep_customer_btn.setVisibility(View.GONE);
		
		rep_acctype_label.setVisibility(View.GONE);
		rep_acctype_btn.setVisibility(View.GONE);
		
		rep_firm_label.setVisibility(View.GONE);
		rep_firm_btn.setVisibility(View.GONE);
		
	}
		
	
	private DialogInterface.OnClickListener AccTypeCursor_DialogSelect = new DialogInterface.OnClickListener() {
	    public void onClick(DialogInterface dialog, int which) {
	    	
	    	AccTypeCursor.moveToPosition(which);
	    	ProcessWidgetsByReportItem ();
	    	dialog.dismiss();	    	
	    	
	  }		
	};
	
	private DialogInterface.OnClickListener FirmCursor_DialogSelect = new DialogInterface.OnClickListener() {
	    public void onClick(DialogInterface dialog, int which) {
	    	   	
	    	FirmCursor.moveToPosition(which);
	    	ProcessWidgetsByReportItem ();
	    	dialog.dismiss();	    		   
	    	
	  }		
	};	
	
	private void ProcessWidgetsByReportItem () {		
		
		ReportsFieldsCursor = MainGlobalModule.DBE.rawQuery("select reports_field from xref_reportsfields where reports_id = ?", new String [] {ReportsCursor.getString(0)});
		
		rep_replist_btn.setTag(ReportsCursor.getString(0));
    	rep_replist_btn.setText(ReportsCursor.getString(1));
    	
		rep_firm_btn.setTag(FirmCursor.getString(0));
    	rep_firm_btn.setText(FirmCursor.getString(1));
    	
    	rep_acctype_btn.setTag(AccTypeCursor.getString(0));
    	rep_acctype_btn.setText(AccTypeCursor.getString(1));
    	
		HideAll ();
		
		ReportsFieldsCursor.moveToFirst();
		while (!ReportsFieldsCursor.isAfterLast()){
		
			String Field = ReportsFieldsCursor.getString(0);		
			
			if (Field.equals("DateBegin")) {
				rep_datebeg_label.setVisibility(View.VISIBLE);
				rep_datebeg_btn.setVisibility(View.VISIBLE);					
			}
			
			if (Field.equals("DateEnd")) {
				rep_dateend_label.setVisibility(View.VISIBLE);
				rep_dateend_btn.setVisibility(View.VISIBLE);					
			}
			
			if (Field.equals("Customers")) {
				rep_customer_label.setVisibility(View.VISIBLE);			
				rep_customer_btn.setVisibility(View.VISIBLE);		
			}
			
			if (Field.equals("Firm")) {
				rep_firm_label.setVisibility(View.VISIBLE);
				rep_firm_btn.setVisibility(View.VISIBLE);					
			}
			
			if (Field.equals("AccType")) {
				rep_acctype_label.setVisibility(View.VISIBLE);
				rep_acctype_btn.setVisibility(View.VISIBLE);					
			}
			
			ReportsFieldsCursor.moveToNext();
			
		}
		
	}	
	
	private DialogInterface.OnClickListener ReportsCursor_DialogSelect = new DialogInterface.OnClickListener() {
	    public void onClick(DialogInterface dialog, int which) {
	    	 
	    	
	    	ReportsCursor.moveToPosition(which);
	    	ProcessWidgetsByReportItem ();
	    	dialog.dismiss();
	    	
	  }		
	};
	

	private void GetReportsCursor () {
	
		ReportsCursor = MainGlobalModule.DBE.rawQuery("select id as _id, descr , descr_full, reportfile from xref_reports order by descr asc", null);
		if (ReportsCursor.getCount()>0) {
			ReportsCursor.moveToFirst();	
		}
		else{
			Toast xtoast = Toast.makeText(Ctx, "нет отчетов !", Toast.LENGTH_SHORT);
			xtoast.show(); 
			finish();
		}	
	
	}
	
	
	private void GetAccTypeCursor () {
		
		AccTypeCursor = MainGlobalModule.DBE.rawQuery("select id as _id, descr from xenum_AccType union select -1 as id, 'Упр+Общ' as descr order by descr asc", null);
		if (AccTypeCursor.getCount()>0) {
			AccTypeCursor.moveToFirst();	
		}
		else{
			Toast xtoast = Toast.makeText(Ctx, "нет типов учета!", Toast.LENGTH_SHORT);
			xtoast.show(); 
			finish();
		}	
	
		
	}
	
	private void GetFirmCursor () {
	
		FirmCursor = MainGlobalModule.DBE.rawQuery("select id as _id, descr from xref_Firms order by descr asc", null);
		if (FirmCursor.getCount()>0) {
			FirmCursor.moveToFirst();	
		}
		else{
			Toast xtoast = Toast.makeText(Ctx, "Нет фирм !", Toast.LENGTH_SHORT);
			xtoast.show(); 
			finish();
		}	
	
	}

	
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {	
		 
		 switch(requestCode) { 
		    case IDR_CustomerSelect:
		    	if (resultCode==RESULT_OK) {
		    		rep_customer_btn.setTag(data.getStringExtra("customer_id"));
		    		rep_customer_btn.setText(data.getStringExtra("customer_descr"));
		    	}
		    	break;
		 }
		    	   	
	};
	
	private OnClickListener rep_repgo_ibtn_click = new OnClickListener() {
		@Override
		public void onClick(View v) { 
			GetReportFromServer ();
		}
	};
	
	
	private void GetReportFromServer () {
		
		pd.show();
		
		ReportLoader rl = new ReportLoader();
		rl.execute();
		
	}
	
	class ReportLoader extends AsyncTask<String, String, String> {

		@Override
		protected String doInBackground(String... arg0) {
		
			StringBuilder ParamArray = new StringBuilder();				
			ParamArray.append(String.format ("%s=%s;","Customer",rep_customer_btn.getTag()));
			ParamArray.append(String.format ("%s=%s;","DateBegin",MainGlobalModule.DateToSqlString(((Calendar)rep_datebeg_btn.getTag ()).getTime())));
			ParamArray.append(String.format ("%s=%s;","DateEnd",MainGlobalModule.DateToSqlString(((Calendar)rep_dateend_btn.getTag ()).getTime())));
			ParamArray.append(String.format ("%s=%s;","AccType",rep_acctype_btn.getTag()));		
			ParamArray.append(String.format ("%s=%s;","Firm",rep_firm_btn.getTag()));
			ParamArray.append(String.format ("%s=%s;","ManagerId",MainGlobalModule.SettingsCollection.get("ManagerId")));		
			String ParamArrayString = ParamArray.toString();
		
			StringBuilder decodedString = new StringBuilder();
			
			try {
				
				SetCurrentURLString ();
				
				URL xUrl = GetWebServiceURL(CurrentURLString);						
				HttpURLConnection urlConnection;
			
				urlConnection = (HttpURLConnection) xUrl.openConnection();
				urlConnection.addRequestProperty("XeniaActionName", "GetExtReport");
				urlConnection.addRequestProperty("DeviceId",URLEncoder.encode(MainGlobalModule.SettingsCollection.get("DeviceId")));
				urlConnection.addRequestProperty("ManagerId",URLEncoder.encode(MainGlobalModule.SettingsCollection.get("ManagerId")));
				urlConnection.addRequestProperty("ExtReportName", URLEncoder.encode(ReportsCursor.getString(3)));			
				urlConnection.addRequestProperty("ExtReportParam", URLEncoder.encode(ParamArrayString));				
				urlConnection.setDoOutput(true);
				urlConnection.setChunkedStreamingMode(0);
				urlConnection.connect();
				
				BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));				
				String decodedStringPart; 
				while ((decodedStringPart = in.readLine()) != null) {
					decodedString.append(decodedStringPart);
		    		}
				in.close();
			
				urlConnection.disconnect();				
			
			}
		
			catch (Exception e) {
			
				e.printStackTrace();
			
			}
			
			return decodedString.toString ();
			
		}
		
		@Override
		protected void onPostExecute(String result) {
			
			super.onPostExecute(result);
			
			pd.dismiss();
			
			Intent htmlview = new Intent ();
			htmlview.setClass(Ctx, Activity_ExtReportsHTML.class);
			htmlview.putExtra("HtmlString", result);
			startActivity(htmlview);
			
		}
		
	}
	
}
